package com.favccxx.search.application;

import com.favccxx.search.domain.project.Project;
import com.favccxx.search.domain.project.ProjectRepo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author favccxx
 * @date 5/13/2020 3:13 PM
 */
@Service
public class ProjectService {

    @Autowired
    ProjectRepo projectRepo;

    /**
     * Get Project by project id
     *
     * @param id
     * @return
     */
    public Project findById(String id) {
        Optional<Project> opt = projectRepo.findById(id);
        if (opt.isPresent()) {
            return opt.get();
        }
        return null;
    }

    /**
     * find all projects
     *
     * @return
     */
    public List<Project> findAll() {
        return projectRepo.findAll();
    }

    /**
     * Insert project
     *
     * @param project
     */
    public void insert(Project project) {
        projectRepo.insert(project);
    }

    /**
     * Update project by id
     *
     * @param project
     * @return
     */
    public void update(Project project) {
        if (StringUtils.isNotBlank(project.getId())) {
            Optional<Project> opt = projectRepo.findById(project.getId());
            if (opt.isPresent()) {
                Project existProject = opt.get();

                if (StringUtils.isNotBlank(project.getName())) {
                    existProject.setName(project.getName());
                }

                if (StringUtils.isNotBlank(project.getDescription())) {
                    existProject.setName(project.getDescription());
                }

                if (StringUtils.isNotBlank(project.getStatus())) {
                    existProject.setName(project.getStatus());
                }

                projectRepo.save(existProject);
            }
        } else {
            projectRepo.save(project);
        }
    }

    /**
     * delete project by id
     *
     * @param id
     */
    public void deleteById(String id) {
        // TODO: need to check data source etc.
    }

}
